/**
 * 处理群成员数据
 */
import { keywordCompare } from '@gnlab/utils'
import pick from 'lodash/pick'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { GroupContact } from '@/services/contact-types/groups'
import type { BaseContact } from '@/services/contacts'

/**
 * 用于 @ 的群成员数据
 */
export type AtMember = Pick<BaseContact, 'userId' | 'name' | 'avatar'>
export type AtMembers = [AtMember] & AtMember[]

/**
 * 格式化群成员数据
 */
export function useMembers(params: {
  contact: GroupContact
  search: string | null // 为 null 代表未开启 @ 视图
}): AtMember[] {
  const { contact, search } = params
  const [allMembers] = useStreams(services.groups.members)

  const members = useMemo(() => {
    if (search === null || !allMembers.length) return [] // 未开启 @，或未获取到成员列表，则不处理成员数据（也不会把 "@所有人" 显示出来）

    const atAll = { userId: '0', name: '所有人', avatar: '' }
    return [atAll, ...allMembers]
      .map(member => ({
        ...pick(member, 'userId', 'avatar'),
        name: member.name || member.userId, // 有些群成员没获取到名称，用 userId 代替
      }))
      .filter(member => {
        if (member.userId === contact.ownerWxid) return false // 忽略自己
        return search ? keywordCompare(search, member.name) : true // @所有人 也参与搜索，因为用户找不到这个选项时可能真的想搜到它
      })
      .sort((memberA, memberB) => {
        if (memberA.userId === '0') return -1 // @所有人 放最前面
        if (memberB.userId === '0') return 1
        if (memberA.userId === contact.creatorWxid) return -1 // 群主 放在下一个
        if (memberB.userId === contact.creatorWxid) return 1
        return 0
      })
  }, [allMembers, contact, search])

  return members
}

/**
 * 生成 member 元素的 id
 */
export function makeElementId(memberUserId: string) {
  return `at-member-${memberUserId}`
}
